package com.thinkgem.jeesite.kpoint.core.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thinkgem.jeesite.common.persistence.BasePage;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author:Kongxiangsheng
 * @DesCription:
 * @Date:Created in 17:54 2018/12/5
 * @Modified By:
 */
@Slf4j
public abstract class KpointBaseController<EntityService extends KpointBaseService, Entity extends KpointBaseEntityPK> extends BaseController {
    @Autowired
    protected EntityService entityService;

    /**
     * 得到页面路径
     *
     * @return
     */
    protected abstract String getPagePath();

    /**
     * 得到模块
     *
     * @return
     */
    protected abstract String getModule();

    /**
     * 得到entity名
     *
     * @return
     */
    protected abstract String getEntity();

    @RequestMapping(value = {"list", ""})
    public String list(Entity entity, HttpServletRequest request, HttpServletResponse response, Model model) {
        BasePage<Entity> page = new BasePage<Entity>(request, response);
        entityService.page(page, new QueryWrapper<Entity>(entity));

        model.addAttribute("page", page);
        return getPagePath() + "list";
    }

    @RequestMapping("form")
    public String form(Entity entity, Model model) {
        if (StringUtils.isNotBlank(entity.getId())) {
            entity = (Entity) entityService.getById(entity.getId());
        }
        model.addAttribute(getEntity(), entity);
        return getPagePath() + "form";
    }

    @RequestMapping(value = "save")
    public String save(Entity entity, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, entity)) {
            return form(entity, model);
        }
        entityService.saveOrUpdate(entity);
        addMessage(redirectAttributes, "保存成功");
        return "redirect:" + adminPath + "/" + getModule() + "/" + getEntity() + "/?repage";
    }

    @RequestMapping(value = "delete")
    public String delete(Entity entity, RedirectAttributes redirectAttributes) {
        entityService.removeById(entity.getId());
        addMessage(redirectAttributes, "删除成功");
        return "redirect:" + adminPath + "/" + getModule() + "/" + getEntity() + "/?repage";
    }

}
